package py.com.fms.session;

import java.math.BigDecimal;
import java.util.Collection;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.faces.FacesMessages;

import py.com.fms.fms.bean.*;
import py.com.fms.utilities.DateAssistant;
import py.com.fms.com.bean.*;
import py.com.fms.com.session.transactions.TrnPurchaseOrder;

@Name("comAssist")
@Scope(ScopeType.SESSION)
public class ComAssistant {
	private BigDecimal taxTotal;
	private BigDecimal exemptTotal;
	private BigDecimal taxedTotal;

	
	public void processTax(IvaBean tax, BigDecimal itemTotal){
		if(tax == null){	
			System.out.println("TAX IS NULL");
		}else{
			Double percent = tax.getPercentage();
			Double divider = new Double(100);
			Double mult = (percent/divider);
			System.out.println("IVA PERCENT: " + percent);
			System.out.println("Item Total: " + itemTotal);
			if(percent > 0){
				System.out.println("IVA MAYOR A 0: " + percent);
				Double tt = new Double(itemTotal.doubleValue()*(mult));
				System.out.println("TAXED: " + tt);
				Double roundedTaxedTotal = round(tt, 5);
				this.taxedTotal = new BigDecimal(Double.toString(roundedTaxedTotal));
				this.exemptTotal = new BigDecimal(0);
				this.taxTotal = this.taxedTotal;
			}
			
			if(percent.equals(new Double(0))){
				this.taxedTotal = new BigDecimal(0);
				this.exemptTotal = itemTotal;
				this.taxTotal = this.taxedTotal;
			}
		}
		System.out.println("TAXED: " + taxedTotal);
		System.out.println("EXCEMPT: " + exemptTotal);
		System.out.println("TOTAL: " + taxTotal);
	}
	
	
	public Boolean validatePurchaseForm(PurchasesHeadBean purchaseHead, Collection<PurchasesDetBean> allPurchasesDet){
		try{
			if(purchaseHead.getStamping().isEmpty() || purchaseHead.getStamping() == null){
				this.generateErrorMsg("Favor complete todos los campos correctamente", "actionform:buyHeadStamping");
				return false;
			}
			if(purchaseHead.getEstablishment().isEmpty() || purchaseHead.getEstablishment() == null){
				this.generateErrorMsg("Favor complete todos los campos correctamente", "actionform:buyHeadEstablishment");
				return false;
			}
			if(purchaseHead.getExpedition().isEmpty() || purchaseHead.getExpedition() == null){
				this.generateErrorMsg("Favor complete todos los campos correctamente", "actionform:buyHeadExpedition");
				return false;
			}
			if(purchaseHead.getVoucher().isEmpty() || purchaseHead.getVoucher() == null){
				this.generateErrorMsg("Favor complete todos los campos correctamente", "actionform:buyHeadVoucher");
				return false;
			}
			if(purchaseHead.getSupplierData() == null){
				this.generateErrorMsg("Favor complete todos los campos correctamente", "actionform:buyHeadSupplier");
				return false;
			}
			if(purchaseHead.getVoucherDate() == null){
				this.generateErrorMsg("Favor complete todos los campos correctamente", "actionform:buyHeadVoucherDate");
				return false;
			}
			if(purchaseHead.getBuyConditionData() == null){
				this.generateErrorMsg("Favor complete todos los campos correctamente", "actionform:buyHeadBuyCondition");
				return false;
			}
			if(purchaseHead.getBuyConditionData() == null){
				this.generateErrorMsg("Favor complete todos los campos correctamente", "actionform:buyHeadCostCenter");
				return false;
			}
			if(purchaseHead.getBuyTypeData() == null){
				this.generateErrorMsg("Favor complete todos los campos correctamente", "actionform:buyHeadBuyType");
				return false;
			}
			if(purchaseHead.getVoucherData() == null){
				this.generateErrorMsg("Favor complete todos los campos correctamente", "actionform:buyHeadVoucher");
				return false;
			}
			if(purchaseHead.getCurrencyData() == null){
				this.generateErrorMsg("Favor complete todos los campos correctamente", "actionform:buyHeadCurrency");
				return false;
			}
			if(allPurchasesDet.isEmpty() || allPurchasesDet == null){
				this.generateErrorMsg("El detalle de la compra está vacío. Favor inserte el detalle", "actionform:buyInsDetailBtn");
				return false;
			}
		}catch (Exception e) {
			// TODO: handle exception
		}
		return true;	
		
	}
	
	public Boolean validatePurchaseDet(PurchasesDetBean purchaseDet){
		try{
			if(purchaseDet.getSupplyData() == null){
				this.generateErrorMsg("Favor seleccione el Insumo", "actionform:buyDetSupply");
				return false;
			}
			if(purchaseDet.getMeasureUnitData() == null){
				this.generateErrorMsg("Favor seleccione la unidad de medida", "actionform:buyDetMeasureUnit");
				return false;
			}
			if(purchaseDet.getTaxData() == null){
				this.generateErrorMsg("Favor seleccione el IVA", "actionform:buyDetIva");
				return false;
			}
			if(purchaseDet.getQuantity() == null){
				this.generateErrorMsg("Favor ingrese la cantidad a pedir", "actionform:buyDetQuantity");
				return false;
			}else{
				if(purchaseDet.getQuantity() <= new Double(0)){
					this.generateErrorMsg("La cantidad no puede ser igual o menor a cero", "actionform:buyDetQuantity");
					return false;
				}
			}
			if(purchaseDet.getGrossCost() == null){
				this.generateErrorMsg("Favor ingrese el costo", "actionform:buyDetCost");
				return false;
			}else{
				if(purchaseDet.getGrossCost().doubleValue() <= new Double(0)){
					this.generateErrorMsg("El costo no puede ser igual o menor a cero", "actionform:buyDetCost");
					return false;
				}
			}
			if(purchaseDet.getDiscount() != null){
				if(purchaseDet.getDiscount().doubleValue() < new Double(0)){
					this.generateErrorMsg("El descuento no puede ser menor a cero", "actionform:buyDetDiscount");
					return false;
				}else{
					if(purchaseDet.getDiscount().doubleValue() > purchaseDet.getGrossCost().doubleValue()){
						this.generateErrorMsg("El descuento no puede ser mayor al costo", "actionform:buyDetDiscount");
					}
				}
			}
			
			if(purchaseDet.getCharge() != null){
				if(purchaseDet.getCharge().doubleValue() < new Double(0)){
					this.generateErrorMsg("El recargo no puede ser o menor a cero", "actionform:buyDetCharge");
					return false;
				}
			}
			
		}catch (Exception e) {
			// TODO: handle exception
		}
		return true;
	}
	
	public void validateQuant(Object arg){
		if((Long)arg <= 0){
			FacesMessages.instance().add("Cantidad Invalida");
			TrnPurchaseOrder.setCanSave(false);
		}
	}
	
	
	public void validateStringInput(String field){
		if(field.isEmpty() || field == null){
			System.out.println("Validating String: " + field);
			this.generateErrorMsg("Favor ingrese el Timbrado", "actionform:headStamping");
		}else{
		}
	}
	
	
	public Boolean validateOrderHead(OrderHeadBean orderHead, Collection<OrderDetBean> allOrderDet){
		try{
			if(orderHead.getSupplierData() == null){
				this.generateErrorMsg("Favor seleccione el proveedor", "actionform:orderSupplier");
				return false;
			}
			if(orderHead.getBuyConditionData() == null){
				this.generateErrorMsg("Favor seleccione la condicion de compra", "actionform:orderBuyConditionData");
				return false;
			}
			if(orderHead.getBuyConditionData() == null){
				this.generateErrorMsg("Favor seleccione el Centro de Costo", "actionform:orderCostCenter");
				return false;
			}
			if(orderHead.getBuyTypeData() == null){
				this.generateErrorMsg("Favor seleccione el Tipo de Compra", "actionform:orderBuyType");
				return false;
			}
			if(orderHead.getCurrencyData() == null){
				this.generateErrorMsg("Favor seleccione la Moneda", "actionform:orderCurrency");
				return false;
			}
			if(orderHead.getDeliveryDate() == null){
				this.generateErrorMsg("Seleccione la fecha de entrega", "actionform:orderDeliverDate");
				return false;
			}else{
				if(orderHead.getDeliveryDate().before(DateAssistant.getCurrentDate())){
					this.generateErrorMsg("Fecha de entrega no puede ser menor a la Fecha Actual", "actionform:orderDeliverDate");
					return false;
				}
			}
			if(allOrderDet.isEmpty() || allOrderDet == null){
				this.generateErrorMsg("El detalle del Pedido está vacío. Favor inserte el detalle", "actionform:orderInsDetailBtn");
				return false;
			}
			
		}catch (Exception e) {
			// TODO: handle exception
		}
		return true;
	}
	
	public Boolean validateOrderDet(OrderDetBean orderDet){
		try{
			if(orderDet.getSupplyData() == null){
				this.generateErrorMsg("Favor seleccione el Insumo", "actionform:orderDetSupply");
				return false;
			}
			if(orderDet.getMeasureUnitData() == null){
				this.generateErrorMsg("Favor seleccione la unidad de medida", "actionform:orderDetMeasureUnit");
				return false;
			}
			if(orderDet.getTaxData() == null){
				this.generateErrorMsg("Favor seleccione el IVA", "actionform:orderDetIva");
				return false;
			}
			if(orderDet.getQuantity() == null){
				this.generateErrorMsg("Favor ingrese la cantidad a pedir", "actionform:orderDetQuantity");
				return false;
			}else{
				if(orderDet.getQuantity() <= new Double(0)){
					this.generateErrorMsg("La cantidad no puede ser igual o menor a cero", "actionform:orderDetQuantity");
					return false;
				}
			}
			if(orderDet.getGrossCost() == null){
				this.generateErrorMsg("Favor ingrese el costo", "actionform:orderDetCost");
				return false;
			}else{
				if(orderDet.getGrossCost().doubleValue() <= new Double(0)){
					this.generateErrorMsg("El costo no puede ser igual o menor a cero", "actionform:orderDetCost");
					return false;
				}
			}
			if(orderDet.getDiscount() != null){
				if(orderDet.getDiscount().doubleValue() < new Double(0)){
					this.generateErrorMsg("El descuento no puede ser menor a cero", "actionform:orderDetDiscount");
					return false;
				}else{
					if(orderDet.getDiscount().doubleValue() > orderDet.getGrossCost().doubleValue()){
						this.generateErrorMsg("El descuento no puede ser mayor al costo", "actionform:orderDetDiscount");
					}
				}
			}
			
			if(orderDet.getCharge() != null){
				if(orderDet.getCharge().doubleValue() < new Double(0)){
					this.generateErrorMsg("El recargo no puede ser o menor a cero", "actionform:orderDetCharge");
					return false;
				}
			}
			
		}catch (Exception e) {
			// TODO: handle exception
		}
		return true;
	}
	
	
	public void generateErrorMsg(String msg, String uiObject){
		String errorMessage = msg;
		FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR,errorMessage,errorMessage);
		FacesContext.getCurrentInstance().addMessage(uiObject, message);
		
	}
	
	public void generateInfoMsg(String msg, String uiObject){
		String errorMessage = msg;
		FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,errorMessage,errorMessage);
		FacesContext.getCurrentInstance().addMessage(uiObject, message);
		
	}
	
	
	public static Double round(Double param, int decimalPlace){
	    // Para n�meros con punto flotante (es decir, con parte decimal) la forma 
		// recomendada de construir un objeto BigDecimal es a trav�s de un String. 
	    BigDecimal rounded = new BigDecimal(Double.toString(param));
	    rounded = rounded.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
	    return rounded.doubleValue();
	  }

	
	public Boolean validatePaymentOrderTotal(BigDecimal totalPaymentOrder, BigDecimal totalMethodOfPayment){
		System.out.println("");
		if (!totalPaymentOrder.toString().equals(totalMethodOfPayment.toString())) {
			this.generateErrorMsg("Los totales no coinciden", "");
			return false;
		}else
			return true;
	}
	
	public String getInvoiceNumber(String establishment, String expedition, String voucher, Integer instalments){
		String invoiceNumber = (" Nro. Factura: ").concat(establishment.concat("-".concat(expedition).concat("-".concat(voucher).concat(" Cuota: ".concat(instalments.toString())))));
		return invoiceNumber;
	}
	
    public String getConcatBankAccount(String pBank, String pBankAccountNumber){
    	String myConcat = "Banco: ".concat(pBank).concat(" Nro.Cuenta: ").concat(pBankAccountNumber);
    	return myConcat;
    }

	// ACCESSORS AND MUTATORS

	public BigDecimal getTaxTotal() {
		return taxTotal;
	}

	public void setTaxTotal(BigDecimal taxTotal) {
		this.taxTotal = taxTotal;
	}

	public BigDecimal getExemptTotal() {
		return exemptTotal;
	}

	public void setExemptTotal(BigDecimal exemptTotal) {
		this.exemptTotal = exemptTotal;
	}

	public BigDecimal getTaxedTotal() {
		return taxedTotal;
	}

	public void setTaxedTotal(BigDecimal taxedTotal) {
		this.taxedTotal = taxedTotal;
	}


	
	
}
